<?php
  $key    = md5($_REQUEST['getCapsUrl']);
  $dbconn = pg_connect("host=localhost dbname=gc user=postgres");
  $result = pg_query(sprintf(
    "select thumb from getcaps,layers where key = '%s' and name = '%s' and layers.getcaps = getcaps.seq limit 1"
    ,$key
    ,$_REQUEST['name']
  ));
  $thumb  = '';
  file_put_contents('/tmp/maplog',$_REQUEST['getMapUrl']."\n",FILE_APPEND);
  while ($line = pg_fetch_array($result)) {
    $thumb = pg_unescape_bytea($line[0]);
  }
  if ($thumb == '') {
    file_put_contents('/tmp/maplog',"from wms\n",FILE_APPEND);
    $thumb = @file_get_contents($_REQUEST['getMapUrl']);
    pg_query(sprintf(
      "insert into layers(getcaps,name,thumb) select seq,'%s','%s' from getcaps where key = '%s'"
      ,pg_escape_string($_REQUEST['name'])
      ,pg_escape_bytea($thumb)
      ,$key
    ));
  }
  else {
    file_put_contents('/tmp/maplog',"from db\n",FILE_APPEND);
  }
  pg_close($dbconn);

  header('Content-Type:'.$_REQUEST['format']);
  echo $thumb;
?>
